﻿//using FullCoreWebApi.Common;
using FullCoreWebApi.Respository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
//using System.Speech.AudioFormat;
//using System.Speech.Synthesis;
using System.IO;
using FullCoreRepository;
using FullCoreDBModels;
using System.Speech.Synthesis;
using System.Speech.AudioFormat;

namespace FullCoreControllers
{
    /// <summary>
    /// 接口工具控制着器
    /// </summary>

    public class InterfaceToolController : APIControllerRoot
    {
        private readonly InterfaceToolRepository repository;
        /// <summary>
        /// 构造函数
        /// </summary>
        public InterfaceToolController(InterfaceToolRepository _repository)
        {
            this.repository = _repository;// new InterfaceToolRepository() ;
        }

        /// <summary>
        /// 获取接口工具数据信息
        ///  2022年3月24日
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<InterfaceToolEntity>> GetInterfaceTool()
        {
            return await repository.GetAllInterfaceTool();
        }

        /// <summary>
        /// 获取接口工具数据信息
        ///  2022年3月24日
        /// </summary>
        /// <param name="interfaceCode">接口编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<InterfaceToolEntity> GetInterfaceToolByCode(string interfaceCode)
        {
            return await repository.GetInterfaceToolByCode(interfaceCode);
        }

        /// <summary>
        /// 保存接口数据信息
        ///  2022年3月24日
        /// </summary>
        /// <param name="interfaceToolList"></param>
        /// <returns></returns>
        [HttpPost]
        public CommonResult SaveInterfaceTool([FromBody] List<InterfaceToolEntity> interfaceToolList)
        {
            var result = repository.SaveInterfaceTool(interfaceToolList);
            return result;
        }

        /// <summary>
        /// 保存接口数据信息,不包含clob字段信息
        ///  2022年3月24日
        /// </summary>
        /// <param name="interfaceToolList"></param>
        /// <returns></returns>
        [HttpPost]
        public CommonResult SaveInterfaceToolNoClob([FromBody] List<InterfaceToolEntity> interfaceToolList)
        {
            var result = repository.SaveInterfaceToolNoBlob(interfaceToolList);
            return result;
        }

        private string GetMD5(string str)
        {
            byte[] buffer = Encoding.Default.GetBytes(str); //将字符串解析成字节数组，随便按照哪种解析格式都行

            MD5 md5 = MD5.Create();  //使用MD5这个抽象类的Creat()方法创建一个虚拟的MD5类的对象。

            byte[] bufferNew = md5.ComputeHash(buffer); //使用MD5实例的ComputerHash()方法处理字节数组。

            string strNew = null;

            for (int i = 0; i < bufferNew.Length; i++)
            {

                strNew += bufferNew[i].ToString("x2");  //对bufferNew字节数组中的每个元素进行十六进制转换然后拼接成strNew字符串

            }
            return strNew;
        }

        [HttpGet]
        public CommonResult Text2Vocie(string text)
        {
            string Target = text.Replace(" ", "");//去除空白
            string fileName = GetMD5(Target);  
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + $"\\wwwroot\\speech\\{fileName}.wav";
            string DicPath = Path.GetDirectoryName(filePath);
            string XDPath = $"/speech/{fileName}.wav";
            if (!Directory.Exists(DicPath))
            {
                try
                {
                    Directory.CreateDirectory(DicPath);
                }
                catch (Exception e)
                {
                    return new CommonResult() { Result = false, ErrMsg = "创建文件夹报错！" + e.Message };
                }
            }
            try
            {
                if (Target.Length > 65535)
                {
                    return new CommonResult() { Result = false ,ErrMsg="文本过大！"};
                }
                if (!System.IO.File.Exists(filePath))
                {
                    #region 生成音频
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                        PromptBuilder builder = new PromptBuilder();
                        builder.AppendText(Target);
                        synth.Speak(builder);
                    } 
                    #endregion
                }
                #region 音频转base64
                string base64Str = "";
                FileStream stream = new FileStream(filePath, FileMode.Open);
                using (BinaryReader binReader = new BinaryReader(stream))
                {
                    byte[] bytes = binReader.ReadBytes(Convert.ToInt32(stream.Length));
                    base64Str = Convert.ToBase64String(bytes);
                }
                return new CommonResult() { Result = true, ReturnData = base64Str, ErrMsg = XDPath };
                #endregion
            }
            catch (Exception e)
            {
                return new CommonResult() { Result = false, ErrMsg = "文本转语音报错！" +e.Message};
            }
        }
    }
}
